package com.example.smartg;

//import android.app.PendingIntent;
import android.content.Context;
//import android.content.Intent;
//import android.graphics.Bitmap;
//import android.graphics.drawable.Drawable;
//import android.hardware.usb.UsbDevice;
//import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.IBinder;
//import android.util.Base64;
import android.util.Log;
//import android.view.Menu;
//import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
//import android.widget.ImageButton;
//import android.widget.ImageView;
//import android.widget.TextView;

import com.example.smartg.ui.dashboard.DashboardFragment;
import com.example.smartg.ui.home.HomeFragment;
import com.example.smartg.ui.weixin.WeixinScanFragment;
//import com.example.smartg.utils.ToastUtil;
//import com.zkteco.android.biometric.core.device.ParameterHelper;
//import com.zkteco.android.biometric.core.device.TransportType;
//import com.zkteco.android.biometric.core.utils.LogHelper;
//import com.zkteco.android.biometric.core.utils.ToolUtils;
//import com.zkteco.android.biometric.module.fingerprintreader.FingerprintCaptureListener;
//import com.zkteco.android.biometric.module.fingerprintreader.FingerprintSensor;
//import com.zkteco.android.biometric.module.fingerprintreader.FingprintFactory;
//import com.zkteco.android.biometric.module.fingerprintreader.ZKFingerService;
//import com.zkteco.android.biometric.module.fingerprintreader.exception.FingerprintException;

//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONObject;
//
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
//import okhttp3.Call;
//import okhttp3.Response;


public class LoginNavActivity extends AppCompatActivity {

    private Fragment passwordFragment;
    private Fragment phoneFragment;
    private Fragment wx_scanFragment;
    private Button passwordBtn;
    private Button phoneBtn;
    private Button wx_scanBtn;

    //加上计时器
    private Timer mTimer; // 计时器，每2秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_nav);
        passwordBtn = (Button) findViewById(R.id.password_login);
        phoneBtn = (Button) findViewById(R.id.phone_login);
        wx_scanBtn = (Button) findViewById(R.id.wx_scan_btn);
        passwordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tab(1);
            }
        });
        phoneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tab(2);
            }
        });
        wx_scanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tab(3);
            }
        });
        tab(1);
        // 开启指纹机器
//        startFingerprintSensor();
//        initUSBPermission();
//        beginFinger();
//        //
//        ZKFingerService.clear();
//        getAllFingerprints();
        // 启动计时器
        startTimer();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    //判断是否要收起键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        //如果目前得到焦点的这个view是editText的话进行判断点击的位置
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            // 点击EditText的事件，忽略它。
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上
        return false;
    }

    //隐藏软键盘并让editText失去焦点
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            //这里先获取InputMethodManager再调用他的方法来关闭软键盘
            //InputMethodManager就是一个管理窗口输入的manager
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (passwordFragment != null) {
            transaction.hide(passwordFragment);
        }
        if (phoneFragment != null) {
            transaction.hide(phoneFragment);
        }
    }

    private void tab(int i) {
        resetBtn();
        FragmentManager manager = getSupportFragmentManager();
        //获取FragmentTransaction对象
        FragmentTransaction transaction = manager.beginTransaction();
        //先隐藏所有的Fragment
        hideFragments(transaction);
        switch (i) {
            case 1:
                if (passwordFragment == null) {
                    passwordFragment = new HomeFragment();
                    transaction.add(R.id.content, passwordFragment);
                } else {
                    //如果第一页对应的Fragment已经实例化，则直接显示出来
                    transaction.show(passwordFragment);
                }
                passwordBtn.setBackground(getDrawable(R.drawable.btn_press));
                break;
            case 2:
                if (phoneFragment == null) {
                    phoneFragment = new DashboardFragment();
                    transaction.add(R.id.content, phoneFragment);
                } else {
                    //如果第一页对应的Fragment已经实例化，则直接显示出来
                    transaction.show(phoneFragment);
                }
                phoneBtn.setBackground(getDrawable(R.drawable.btn_press));
                break;
            case 3:
                if (wx_scanFragment == null) {
                    wx_scanFragment = new WeixinScanFragment();
                    transaction.add(R.id.content, wx_scanFragment);
                } else {
                    //如果第一页对应的Fragment已经实例化，则直接显示出来
                    transaction.show(wx_scanFragment);
                }
                wx_scanBtn.setBackground(getDrawable(R.drawable.btn_press));
                break;

        }
        transaction.commit();
    }

    private void resetBtn() {
        passwordBtn.setBackground(getDrawable(R.drawable.btn_nopress));
        phoneBtn.setBackground(getDrawable(R.drawable.btn_nopress));
        wx_scanBtn.setBackground(getDrawable(R.drawable.btn_nopress));
    }

    // 指纹识别器
//    private static final int VID = 6997;
//    private static final int PID = 288;
//    private FingerprintSensor fingerprintSensor = null;
//    private final String ACTION_USB_PERMISSION = "com.example.smartg.USB_PERMISSION";

//    private void initUSBPermission() {
//        UsbManager usbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
//        for (UsbDevice device : usbManager.getDeviceList().values()) {
//            if (device.getVendorId() == VID && device.getProductId() == PID) {
//                Intent intent = new Intent(ACTION_USB_PERMISSION);
//                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
//                usbManager.requestPermission(device, pendingIntent);
//            }
//        }
//    }


//    private void startFingerprintSensor() {
//        // Define output log level
//        LogHelper.setLevel(Log.ASSERT);
//        LogHelper.setNDKLogLevel(Log.ASSERT);
//        // Start fingerprint sensor
//        Map fingerprintParams = new HashMap();
//        //set vid
//        fingerprintParams.put(ParameterHelper.PARAM_KEY_VID, VID);
//        //set pid
//        fingerprintParams.put(ParameterHelper.PARAM_KEY_PID, PID);
//        fingerprintSensor = FingprintFactory.createFingerprintSensor(this, TransportType.USB, fingerprintParams);
//    }

//    public void beginFinger() {
//        try {
//            fingerprintSensor.open(0);
//            final FingerprintCaptureListener listener = new FingerprintCaptureListener() {
//                @Override
//                public void captureOK(final byte[] fpImage) {
//                }
//
//                @Override
//                public void captureError(FingerprintException e) {
//                }
//
//                @Override
//                public void extractError(final int err) {
//                    Log.e("extractError", Integer.toString(err));
//                }
//
//                @Override
//                public void extractOK(final byte[] fpTemplate) {
//                    final byte[] tmpBuffer = fpTemplate;
//                    final int templateLen = fingerprintSensor.getLastTempLen();
//                    //Base64 Template
//                    //String strBase64 = Base64.encodeToString(tmpBuffer, 0, templateLen, Base64.NO_WRAP);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
////
//                            byte[] bufids = new byte[256];
//                            int ret = ZKFingerService.identify(tmpBuffer, bufids, 70, 1);
//                            if (ret > 0) {
//                                String strRes[] = new String(bufids).split("\t");
//                                String user_id = strRes[0];
//                                get_token(user_id);
//                            } else {
//                                ToastUtil.error(LoginNavActivity.this, "验证失败！");
//                            }
//                        }
//                    });
//                }
//
//
//            };
//            fingerprintSensor.setFingerprintCaptureListener(0, listener);
//            fingerprintSensor.startCapture(0);
//            Log.e("open", "start capture succ");
//        } catch (FingerprintException e) {
//            Log.e("open", "start capture unsucc");
//        }
//    }

//    public void stopFinger() {
//        try {
//            //stop capture
//            fingerprintSensor.stopCapture(0);
//            fingerprintSensor.close(0);
//            Log.e("OnBnStop", "success");
//
//        } catch (FingerprintException e) {
//            Log.e("OnBnStop", e.toString());
//        }
//
//    }


    @Override
    protected void onDestroy() {
//        stopFinger();
        stopTimer();
        super.onDestroy();

    }
    @Override
    protected void onPause() {
        stopTimer();
        super.onPause();

    }


    @Override
    protected void onStop() {
        super.onStop();
//        stopFinger();
        stopTimer();
    }

//    public void get_token(String user_id) {
//        String url = "http://10.2.47.115/smartg_api/fingerprint_manage/fingerprint_login";
//        //实例化
//        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
//        JSONObject json = new JSONObject();
//        try {
//            json.put("user_id", user_id);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e("exception", e.toString());
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        ToastUtil.error(LoginNavActivity.this, "访问出错！");
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String responsedata = response.body().string();
//                Log.e("res2", responsedata);
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(responsedata);
//                    String msg = jsonObject.optString("msg");
//                    int code = jsonObject.optInt("code");
//                    JSONObject data = jsonObject.optJSONObject("data");
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (code == 20000) {
//                                // Log.e("接收sucess", msg);
//                                String token = data.optString("token");
//                                String user_name = data.optString("name");
//                                // 记住用户信息到SharedPreferences
//                                SpUtils.putString(LoginNavActivity.this,"token",token);
//                                SpUtils.putString(LoginNavActivity.this,"user_name",user_name);
//                                ToastUtil.success(LoginNavActivity.this,"验证成功！");
//                                finish();
//                            } else {
//                                ToastUtil.error(LoginNavActivity.this, msg);
//                            }
//                        }
//                    });
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//    }

//    public void getAllFingerprints() {
//        String url = "http://10.2.47.115/smartg_api/fingerprint_manage/get_all_fingerprint";
//        //实例化
//        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
//        JSONObject json = new JSONObject();
//        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e("exception", e.toString());
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        ToastUtil.error(LoginNavActivity.this, "访问出错！");
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String responsedata = response.body().string();
//                Log.e("res2", responsedata);
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(responsedata);
//                    String msg = jsonObject.optString("msg");
//                    int code = jsonObject.optInt("code");
//                    JSONArray data = jsonObject.optJSONArray("data");
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (code == 20000) {
//                                // Log.e("接收sucess", msg);
//                                int size = data.length();
//                                if (size > 0) {
//                                    for (int i = 0; i < size; i++) {
//                                        JSONObject user_fingerprint = data.optJSONObject(i);
//                                        String user_id = user_fingerprint.optString("_id");
//                                        String fingerprint = user_fingerprint.optString("fingerprint");
//                                        byte[] regTemp = Base64.decode(fingerprint, Base64.NO_WRAP);
//                                        ZKFingerService.save(regTemp, user_id);
//                                    }
//                                    ToastUtil.success(LoginNavActivity.this, "指纹识别器准备就绪！");
//                                } else {
//                                    ToastUtil.error(LoginNavActivity.this, "指纹库为空！");
//                                }
//
//                            } else {
//                                ToastUtil.error(LoginNavActivity.this, msg);
//                            }
//                        }
//                    });
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//    }
    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            // 1分钟未操作停止计时并退出登录
            long mLastActionTime = SpUtils.getLong(LoginNavActivity.this,"lastActionTime",0);
            Log.e("=1=", (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "");
            if (System.currentTimeMillis() - mLastActionTime - 5000 > 1000 * 60 * 1) {
                stopTimer();
                SpUtils.clear(LoginNavActivity.this);
                finish();
            }

        }
    }

    public void stopTimer() {
        Log.e("=1=", "主页定时任务关闭");
        mTimer.cancel();
    }

    private void startTimer() {
        Log.e("=1=", "主页定时任务启动");
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        SpUtils.putLong(this,"lastActionTime",System.currentTimeMillis());
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 1000);
        //Log.e(TAG, "登录成功开始计时");

    }
}